package tlias.Filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import tlias.utils.JwtUtils;

import java.io.IOException;


@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TliasFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        if(uri.contains("/login")){
            log.info("login");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if (request.getHeader("token")==null || request.getHeader("token").isEmpty()){
            response.setStatus(401);
            response.getWriter().write("token is null");
            log.info("token is null");
            return;
        }
        try {
            JwtUtils.verifyJwt(request.getHeader("token"));
            log.info("token is valid");
            filterChain.doFilter(servletRequest,servletResponse);
        } catch (Exception e) {
            response.setStatus(401);
            response.getWriter().write("token is invalid");
            log.info("token is invalid");
        }
    }

}
